package com.shiwaixiangcun.customer.module.intelligent

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterDeviceList
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.entity.DeviceType
import com.shiwaixiangcun.customer.entity.IntelligentDeviceData
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import kotlinx.android.synthetic.main.activity_intelligent_device.*
import kotlinx.android.synthetic.main.layout_device_detail.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 智能设备页面
 */
class IntelligentDeviceActivity : BaseActivity(), View.OnClickListener {

    companion object {
        /**
         * 获取网络数据成功
         */
        private val SUCCESS = 10
        /**
         * 获取网络数据失败
         */
        private val ERROR = 11
        /**
         * 设备为手表
         */
        private val DEVICE_TYPE_WATCH = 1
        /**
         * 设备为摄像头
         */
        private val DEVICE_TYPE_CAMERA = 2

    }




    var isEmpty = true
    private var emptyView: View? = null
    private var detailView: View? = null
    var mAdapter: AdapterDeviceList? = null
    var mList: ArrayList<DeviceType>? = null
    var strToken: String? = null
    var refreshToken: String? = null
    private var btnAddDevice: Button? = null
    private var headView: View? = null
    private var tvNumberDevice: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_intelligent_device)
        EventUtil.getInstance().register(this)
        initView()
        initData()
    }

    override fun onClick(p0: View?) {

        when (p0) {

            tv_add_device -> {
                readyGo(AddSmartDeviceActivity::class.java)

            }
            back_left -> {
                finish()
            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }



    /**
     * 获取网络数据
     */
    private fun initData() {
        refreshToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
        strToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.get<String>(GlobalApi.getDeviceList)
                .cacheMode(CacheMode.NO_CACHE)
                .params("access_token", strToken)
                .execute(object : StringDialogCallBack(this) {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        showToastShort("网络故障")
                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.GET_DEVICE_LIST, ERROR, false))
                    }
                    override fun onSuccess(response: Response<String>?) {
                        Log.e(BUG_TAG, response?.body().toString())
                        val type = object : TypeToken<DeviceBaseEntity<IntelligentDeviceData>>() {}.type
                        val fromJson = JsonUtil.fromJson<DeviceBaseEntity<IntelligentDeviceData>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.GET_DEVICE_LIST, SUCCESS, fromJson.data))
                            }
                            1002 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.GET_DEVICE_LIST, ERROR, false))

                            }
                            ResponseConfig.TOKEN_INVALID -> {
                                showToastShort("当前登录失效")
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                        }
                    }
                })

    }

    fun initView() {
        tv_page_name.text = "智能设备"
        back_left.setOnClickListener(this)

        detailView = layoutInflater.inflate(R.layout.layout_device_detail, null, false)
        emptyView = layoutInflater.inflate(R.layout.layout_device_empty, null, false)
        headView = layoutInflater.inflate(R.layout.layout_device_header, null, false)
        tvNumberDevice = headView?.findViewById(R.id.tv_list_header)
        contentLayout.removeAllViews()
        mList = ArrayList()
        mAdapter = AdapterDeviceList(mList)

        contentLayout.addView(detailView)
        tv_add_device.setOnClickListener(this)
        rv_device_list.layoutManager = LinearLayoutManager(this)
        rv_device_list.adapter = mAdapter
        val divider = RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.END)
                .setStartSkipCount(1)
                .setMarginLeft(20f)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_device_list.addItemDecoration(divider)
        btnAddDevice = emptyView?.findViewById(R.id.btn_add_device)
        btnAddDevice?.setOnClickListener {

            Log.e(BUG_TAG, "点击跳转")
            intent.setClass(this, AddSmartDeviceActivity::class.java)
            startActivity(intent)

        }

        mAdapter?.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) as DeviceType
            val bundle = Bundle()

            when (item.type) {
                DEVICE_TYPE_CAMERA -> {
                    var isOnline = false
                    val deviceType = adapter.data[position] as DeviceType
                    if (deviceType.desc == "在线") {
                        isOnline = true

                    }
                    bundle.putBoolean("deviceIsOnline", isOnline)
                    bundle.putString("deviceId", item.deviceId)

                    readyGo(SmartCameraInfoActivity::class.java, bundle)
                }
                DEVICE_TYPE_WATCH -> {
                    bundle.putLong("hardwareId", item.hardwareId)
                    readyGo(SmartWatchInfoActivity::class.java, bundle)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {

        when (simpleEvent.mEventType) {
            SimpleEvent.GET_DEVICE_LIST -> {
                when (simpleEvent.mEventValue) {
                    ERROR -> {
                        contentLayout.addView(emptyView)
                        layout_add_device.visibility = View.GONE
                    }
                    SUCCESS -> {
                        mAdapter?.clear()
                        val data = simpleEvent.data as IntelligentDeviceData
                        if ((!data.cameraBinding) && (data.watchData.hardwareId <= 0L)) {
                            layout_add_device.visibility = View.GONE
                            mAdapter?.emptyView = emptyView
                        } else {
                            var deviceNumber = 0
                            if (data.watchData.remainingPower >= 0) {
                                val watchData = data.watchData
                                val watch = DeviceType()
                                watch.type = 1
                                watch.deviceId = ""
                                watch.title = "智能手表"
                                watch.hardwareId = watchData.hardwareId
                                watch.isWhetherAdmin = false
                                watch.cover = R.drawable.device_watch
                                watch.remainingPower = watchData.remainingPower
                                watch.desc = ""
                                mList?.add(watch)
                                deviceNumber += 1
                            }
                            data.cameraListDtoList.map {
                                val camera = DeviceType()
                                camera.type = 2
                                camera.deviceId = it.deviceId
                                camera.title = it.name
                                camera.hardwareId = it.hardwareId
                                camera.isWhetherAdmin = it.whetherAdmin
                                camera.cover = R.drawable.device_camera
                                camera.remainingPower = 0
                                if (it.data.channels[0].channelOnline) {
                                    camera.desc = "在线"
                                } else {
                                    camera.desc = "离线"
                                }
                                mList?.add(camera)

                            }
                            layout_add_device.visibility = View.VISIBLE
                            deviceNumber += data.cameraListDtoList.size
                            tvNumberDevice?.text = "你已添加了${deviceNumber}台智能设备"
                            mAdapter?.addHeaderView(headView)
                            mAdapter?.notifyDataSetChanged()
                        }
                    }
                }
            }
            else -> {
                return
            }
        }


    }

    override fun onDestroy() {

        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }


}
